import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home/index",
  },
  {
    path: "/home",
    name: "Home",
    component: () => import("../views/Home.vue"),
    children: [
      {
        path: "/home/index",
        component: () => import("../views/home/Index"),
      },
      {
        path: "/home/shopCar",
        component: () => import("../views/home/ShopCar"),
      },
      {
        path: "/home/my",
        component: () => import("../views/home/My"),
        meta: {
          needLogin: true,
          roles: ["boss", "mange"],
        },
      },
      {
        path: "/home/classify",
        component: () => import("../views/home/Classify"),
      },
    ],
  },
  {
    path: "/login",
    component: () => import("../views/Login"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin && !localStorage.getItem("isLogin")) {
    next({
      path: "/login",
      query: {
        fromPath: to.path,
      },
    });
  } else if (
    to.meta.roles &&
    !to.meta.roles.includes(localStorage.getItem("role"))
  ) {
    next("/home/index");
  } else {
    next();
  }
});

export default router;
